import request from '@/utils/processRequest';
import { getGlobal } from '@/utils/global';
import axios from 'axios';
import { downFileNew } from '@/api/filePage';
export function uploadMulti(data) {
  return request({
    url: '/file/uploadMulti',
    method: 'post',
    headers: {
      'Content-Type': 'multipart/form-data'
    },
    data
  });
}

export function getFilePage(data) {
  return request({
    url: '/file/page',
    method: 'post',
    data
  });
}

// 查找首页图片
export function findHomePageImages(params) {
  return request({
    url: '/homePageImage/findHomePageImages',
    method: 'get',
    params
  });
}

export async function fileView(id) {
  getGlobal().then((all) => {
    const fileViewUrl = `${all.url}/onlinePreview?fileId=${id}`;
    window.open(fileViewUrl);
  });
}

export async function downFile({
  fileName,
  filePath
}, callback) {
  getGlobal().then((all) => {
    const originUrl = `${all.url}/file/downloadByPath?filePath=${filePath}&fileName=${fileName}`;
    return axios.get(
      originUrl, {
        responseType: 'blob',
        onDownloadProgress: (evt) => {
          const progress = parseInt((evt.loaded / evt.total) * 100);
          callback && callback(progress);
        }
      },
    );
  });
}

export async function windowDownFile(item) {
  !item.fileName && item.originName && (item.fileName = item.originName);
  await downFileNew({
    id: item.id,
    fileName: item.fileName
  }).then(res => {
    const blob = res;
    saveFileToLocal(blob, item.fileName);
  });
}

export function getFileByPath(params) {
  return request({
    url: '/file/viewPhoto',
    method: 'get',
    params
  });
}

const saveFileToLocal = (blob, fileName) => {
  const a = document.createElement('a');
  const url = window.URL.createObjectURL(blob);
  const filename = fileName;
  a.href = url;
  a.download = filename;
  a.click();
  window.URL.revokeObjectURL(url);
  a.remove();
};

// // 查询缩略图
// export function fileFindThumbnail(data) {
//   return request({
//     url: '/file/findThumbnail',
//     method: 'post',
//     data
//   });
// }
